import {defineStore} from 'pinia'
import {type UserState} from '@/store/interface'
import useRouteStore from '@/store/route.ts'

const useUserStore = defineStore('user', {
	state: (): UserState => {
		return {
			token: '',
			refreshToken: '',
			userId: '',
			userName: '',
			avatar: '',
			roles: [],
			permissions: []
		}
	},
	getters: {
		getToken: state => state.token,
		getUserId: state => state.userId,
		getUserName: state => state.userName,
		getRoles: state => state.roles,
		getFreshToken: state => state.refreshToken,
		getPermissions: state => state.permissions
	},
	actions: {
		setToken(token: string) {
			this.token = token
		},
		setUserId(id: string | number) {
			this.userId = id
		},
		setUserName(name: string) {
			this.userName = name
		},
		setRoles(data: string[]) {
			this.roles = data
		},
		setAvatar(url: string) {
			this.avatar = url || 'https://ooo.0x0.ooo/2023/07/26/OiqOIG.jpg'
		},
		setFreshToken(refreshToken: string) {
			this.refreshToken = refreshToken
		},
		setPermissions(permissions: string[]) {
			this.permissions = permissions
		},
		userLogout() {
			this.token = ''
			this.roles = []
			this.userId = ''
			this.userName = ''
			this.refreshToken = ''
			this.avatar = ''
			this.permissions = []
			setTimeout(() => {
				useRouteStore().setTabs([])
				useRouteStore().setKeepAliveName([])
				useRouteStore().setMenuList([])
			}, 1000)
		}
	},
	// persist: true // 所有数据持久化
	persist: {
		key: 'user',
		storage: sessionStorage
	}
})

export default useUserStore
